//
//  SAHomeController.m
//  ShopAssistant
//
//  Created by ZhaoYiding on 2017/11/18.
//  Copyright © 2017年 hyxt. All rights reserved.
//

#import "SAHomeController.h"
#import "XLSlideMenu.h"
@interface SAHomeController ()
@property (nonatomic,copy) NSString * homeURL;
@property (nonatomic,assign) BOOL flag;
@end

@implementation SAHomeController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self buildNav];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webViewReload:) name:@"webViewReload" object:nil];
    
    self.webView.wkWebView.allowsBackForwardNavigationGestures = YES;
}

- (void)buildNav
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

#pragma mark - action

- (void)leftAction
{
    if (![self.webView.wkWebView canGoBack])
    {
        [self.xl_sldeMenu showLeftViewControllerAnimated:YES];
    }
}


- (void)fjkwebView:(FJKWebView *)webview didFinishLoadingURL:(NSURL *)URL
{
    //判断是否有上一层H5页面
    if ([self.webView.wkWebView canGoBack])
    {
        [self deleteWebCache];
        if ([URL.absoluteString isEqualToString:self.homeURL])
        {
            self.homeURL = URL.absoluteString;
            [self buildNav];
            self.xl_sldeMenu.slideEnabled = YES;
        }
        else
        {
            [super buildNav];
            self.xl_sldeMenu.slideEnabled = NO;
            
        }
    }
    else
    {
        self.homeURL = URL.absoluteString;
        [self buildNav];
        self.xl_sldeMenu.slideEnabled = YES;
    }
    
}

- (void)webViewReload:(NSNotification *)notice
{
    [self.webView.wkWebView.backForwardList performSelector:NSSelectorFromString(@"_removeAllItems")];
    [self.webView loadURLString:notice.object[@"content"]];
}

- (void)deleteWebCache {
    
    if([[UIDevice currentDevice].systemVersion floatValue] >=9.0) {
        
        NSSet*websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        
        NSDate*dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
        
    }else{
        
        NSString * libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)objectAtIndex:0];
        
        NSString * cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        
        NSError * errors;
        
        [[NSFileManager defaultManager]removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
    
}

@end
